using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

using SBPweb.Data;

#if SQL2005
namespace SBPweb.Data.SQL2005
{
	
	/// <summary>
	/// This class implements a generic update command factory
	/// </summary>
	/// <typeparam name="T">DomainObject</typeparam>
	public class UpdateCommandFactory<T>: IUpdateFactory<T> where T: Entity
	{

		#region Private fields

		private string mCommandName;
		private List<SqlParameterDescriptor> mParams;

		#endregion

		#region Constructor logic

		/// <summary>
		/// Initializes a new UpdateCommandFactory instance
		/// </summary>
		/// <param name="storedProcCommandName">stored procedure name for update</param>
		public UpdateCommandFactory(string storedProcCommandName)
			: this(storedProcCommandName, null)
		{
		}


		/// <summary>
		/// Initializes a new UpdateCommandFactory instance
		/// </summary>
		/// <param name="storedProcCommandName">stored procedure name for updaze</param>
		/// <param name="parameters">List of paramters of stored procedure</param>
		public UpdateCommandFactory(string storedProcCommandName, List<SqlParameterDescriptor> parameters)
		{
			mCommandName = storedProcCommandName;
			mParams = parameters;
		}

		#endregion

		#region IUpdateFactory<int> Members

		/// <summary>
		/// This method constructs the update command by SqlDatabase and T (DomainObject) parameters
		/// </summary>
		/// <param name="db">SqlDatabase db</param>
		/// <param name="entity">T entity</param>
		/// <returns>SqlCommand</returns>
		public SqlCommand ConstructUpdateCommand(SqlDatabase db, T entity)
		{
			SqlCommand command = db.GetStoredProcCommand(mCommandName);

			string format = "@{0}";

			if (mParams != null)
			{
				foreach (SqlParameterDescriptor sqlpd in mParams)
				{
					db.AddInParameter(command, string.Format(format, sqlpd.ParameterName), sqlpd.ParameterType, sqlpd.Value != null ? sqlpd.Value : entity.GetValue<object>(sqlpd.FieldName));
				}
			}

			return command;
		}

		#endregion

		#region IDbToBusinessEntityNameMapper Members

		/// <summary>
		/// This method maps db parameter names to entity property names
		/// </summary>
		/// <param name="dbParameter">db parameter name</param>
		/// <returns>entity property name</returns>
		public string MapDbParameterToBusinessEntityProperty(string dbParameter)
		{
			return dbParameter;
		}

		#endregion

	}
}
#endif